//
//  WJHomeTopView.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/19.
//

import UIKit

protocol WJHomeTopViewDelegate: AnyObject {
    func topViewDidClickSignedItemView(_ view: WJHomeTopView, state: SignState)
}

class WJHomeTopView: UIView {
    
    weak var delegate: WJHomeTopViewDelegate? = nil
    
    lazy var hStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 10.0
        stackView.translatesAutoresizingMaskIntoConstraints = false
        return stackView
    }()
    
    let unSignedItem = WJHomeTopItem()
    let signedItem = WJHomeTopItem()

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(hStackView)
        
        signedItem.homeTopItemType = .homeTopSignedItem
        signedItem.addTarget(self, action: #selector(clickSignedItemAction(_:)), for: .touchUpInside)
        if let signedCount = try? WJPDFListModel.findSignedFiles().count {
            signedItem.titleLabel.text = "\(signedCount)"
        }
        
        unSignedItem.homeTopItemType = .homeTopUnsignedItem
        unSignedItem.addTarget(self, action: #selector(clickUnsignedItemAction(_:)), for: .touchUpInside)
        if let unSignedCount = try? WJPDFListModel.findUnsignedFiles().count {
            unSignedItem.titleLabel.text = "\(unSignedCount)"
        }
        hStackView.addArrangedSubview(unSignedItem)
        hStackView.addArrangedSubview(signedItem)
        
        hStackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func reload() {
        if let signedCount = try? WJPDFListModel.findSignedFiles().count {
            signedItem.titleLabel.text = "\(signedCount)"
        }
        
        if let unSignedCount = try? WJPDFListModel.findUnsignedFiles().count {
            unSignedItem.titleLabel.text = "\(unSignedCount)"
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func clickSignedItemAction(_ sender: UIControl) {
        delegate?.topViewDidClickSignedItemView(self, state: .signed)
    }
    
    @objc func clickUnsignedItemAction(_ sender: UIControl) {
        delegate?.topViewDidClickSignedItemView(self, state: .unSigned)
    }
}
